//
//  ContactVC.swift
//  YueChat
//
//  Created by 1 on 2024/9/16.
//

import UIKit

@available(iOS 13.0, *)
class ContactVC: BaseVC,ContactSearchDelegate {
    
    
    var tagArray : [String] = []
    var tagImgArray : [String] = []
    var allDataArray : [String: Any]?
//    var indexArray : Array<Any> = []
    // 排序后分组数据
    private var objectsArray : [[Any]]?
    // 头部标题keys
    private var keysArray:[String]? = []
    
    var searchHead = SearchView()
    
    var myUser = DMCCUser()
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        showRed()
    }

   
    override func viewDidLoad() {
        super.viewDidLoad()

//        title = "通讯录"
        
//        self.tabBarController?.tabBar.showBadgeOnItemIndex(1)
        setup()
        self.getUserInfo()
        self.requestData()
        self.getListData()
        
        
        DispatchQueue.main.asyncAfter(deadline: .now() + 2, execute: DispatchWorkItem(block: {
            self.requestData()
        }))
    }

    func showRed() {
        GK_main_async_safe {
            let count = gosnFriend.getAddFreiendCount()
            if count > 0 {
                InfoManager.shared.tabbar!.showPointMarkIndex(1)
            }else{
                InfoManager.shared.tabbar!.hideMarkIndex(1)
            }
            self.tableView.reloadData()
        }
    }


    @objc func getListData() {
//        dataSource.removeAll()
        
        Task {
            let array = await gosnFriend.fetchFriendList()
            
            await MainActor.run {
                if array.count > 0 {
                    requestData()
                }
            }
        }
        
        DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: DispatchWorkItem(block: {
            self.tableView.mj_header?.endRefreshing()
        }))
    }
    
    func requestData () {
        dataSource.removeAll()
//        let friendArr = osnFriend.getFriendList()
        let friendArr = gosnFriend.getFriendList()
        for f in friendArr {
            getUser(friendId: f.friendId, count: friendArr.count)
        }
    }
//    friendID    String    "OSNUiHLSx3nxg3uZ8B7zssMcFJRN74Av5JQZmKnAdrmH7BhtFU2x7TjXsThd36EQgRuW6GaPofkHMJ"
    func getUser (friendId:String,count:Int) {

        let user = gosnUser.getUserInfoDefault(friendId) as DMCCUser
//        let user = gosnUser.getUserInfo("OSNUiHLSx3nxg3uZ8B7zssMcFJRN74Av5JQZmKnAdrmH7BhtFU2x7TjXsThd36EQgRuW6GaPofkHMJ")! as DMCCUser
        dataSource.append(user)
        if dataSource.count == count {
            self.sort()
        }
        
    }
    
    
    
    func sort () {
        DispatchQueue.global().async {

            UILocalizedIndexedCollation.getCurrentKeysAndObjectsData(needSortArray: self.dataSource as NSArray) { (dataArray,titleArray) in
                self.objectsArray = dataArray
                self.keysArray    = titleArray
                GK_main_async_safe {
                    self.tableView.reloadData()
                }
                DispatchQueue.main.asyncAfter(deadline: .now() + 3) { [self] in
                    self.tableView.reloadData()
                }
            }
        }
    }
    
    func getUserInfo () {
        myUser = gosnUser.getUserInfoDefault(gosnUser.myId())
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 60
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return keysArray!.count + 1
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return tagArray.count
        }
        
        let array = objectsArray![section - 1] as Array<Any>
        return array.count
    }
    
    //MARK: 这是Setion标题 以及右侧索引数组设置
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        if section != 0 {
            return keysArray?[section - 1]
        }
        return ""
    }
    func sectionIndexTitles(for tableView: UITableView) -> [String]? {
        return keysArray
    }
    
    func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {
        tableView.scrollToRow(at: NSIndexPath(row: 0, section: index) as IndexPath, at: .top, animated: true)
        return index
    }
    
    //MARK: 设置表头的高度。如果使用自定义表头，该方法必须要实现，否则自定义表头无法执行，也不会报错
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        
        if section != 0 {
            return 10.0
        }
        return 0
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if indexPath.section == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "ContactHeadCell", for: indexPath) as! ContactHeadCell
            cell.nameLab.text = tagArray[indexPath.row]
            cell.icon.image = UIImage(named: tagImgArray[indexPath.row])
            
            cell.red.isHidden = true
            if indexPath.row == 0 {
                let count = gosnFriend.getAddFreiendCount()
                if count == 1 {
                    cell.red.isHidden = false
                }
            }
            
           
            return cell
        }
        let array = objectsArray![indexPath.section - 1]
        let user = array[indexPath.row] as! DMCCUser
        let cell = tableView.dequeueReusableCell(withIdentifier: "UserCell", for: indexPath) as! UserCell
//        cell.nickName.text = user.getAlias()
//        cell.icon.sd_setImage(with: URL(string: user.portrait), placeholderImage: kUserImage)
        cell.setUserInfo(userInfo: user)
        return cell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        tableView.deselectRow(at: indexPath, animated: true)
        
        if indexPath.section == 0 {
            if indexPath.row == 0 {
                self.navigationController?.pushViewController(NewFriendVC(), animated: true)
            }else{
                self.navigationController?.pushViewController(MyGroupVC(), animated: true)
            }
        }else {
            let array = objectsArray![indexPath.section - 1]
            let user = array[indexPath.row]
            self.navigationController?.pushViewController(UserDetailVC(userInfo: user as! DMCCUser), animated: true)
        }
    }
    
    @objc func updateList () {
        self.getListData()
    }

    
    func setup () {

        tableStytle = .insetGrouped
        let head = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(getListData))
        head.lastUpdatedTimeLabel?.isHidden = true
        head.stateLabel?.isHidden = true
        self.tableView.mj_header = head
        
        let nib = SearchView.loadFromNib(SearchView())
        
        tableView.separatorInset = UIEdgeInsets(top: 0, left: 76, bottom: 0, right: 0)
        
        searchHead = nib() as! SearchView
        searchHead.searchType = .contact
//        searchHead.blockSearchStr = {[weak self] str in
//            guard let self = self else {return}
//            
//        }
        searchHead.delegate = self
        
        self.tableView.tableHeaderView = searchHead
        
        tableView.register(UINib(nibName: "ContactHeadCell", bundle: nil), forCellReuseIdentifier: "ContactHeadCell")
        tableView.register(UINib(nibName: "UserCell", bundle: nil), forCellReuseIdentifier: "UserCell")
        
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(updateList),
                                               name: NSNotification.Name(rawValue: kDeleteUserChanged),
                                               object: nil)

        geventService.addObserver(OsnEvent.FriendListUpdated, "FriendListUpdated_ContactVC") { [self] data in
            updateList()
        }
        
        geventService.addObserver(OsnEvent.FriendInfoUpdated, "FriendInfoUpdated_ContactVC") { [self] data in
            updateList()
        }
        

        geventService.addObserver(OsnEvent.FriendRequestUpdated, "FriendRequestUpdated_ContactVC") { [self] data in
            showRed()
        }
        
        tagArray = ["新的朋友","群聊"]
        tagImgArray = ["newFriend","groupImg"]
    }
    
    func blockSearchStr(Str: String) {
        searchHead.tf.resignFirstResponder()
        self.navigationController?.pushViewController(SearchVC(), animated: true)
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: kDeleteUserChanged), object: nil)
        geventService.removeObserver(OsnEvent.FriendListUpdated, "FriendListUpdated_ContactVC")
        geventService.removeObserver(OsnEvent.FriendRequestUpdated, "FriendRequestUpdated_ContactVC")
        geventService.removeObserver(OsnEvent.FriendInfoUpdated, "FriendInfoUpdated_ContactVC")
    }
}

extension String {
    func transformToPinYin() ->String {
        let mutableString = NSMutableString(string: self)
        CFStringTransform(mutableString, nil, kCFStringTransformToLatin, false)
        CFStringTransform(mutableString, nil, kCFStringTransformStripDiacritics, false)
        let string = String(mutableString)
        return string.replacingOccurrences(of: " ", with: "").uppercased()
    }
    
    func isNotLetter()-> Bool {
        let upperCaseStr: String = self.uppercased()
        let c = Character(upperCaseStr)
        if  c >= "A", c <= "Z"{//
            return false
        } else {
            return true
        }
    }
}
